﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using SharePointContentGenerator.ContentGeneratorLogic.DataObjects;
using SharePointContentGenerator.ContentGeneratorLogic.SharePointWebServiceCopy;

namespace SharePointContentGenerator.ContentGeneratorLogic.ContentGenerators
{
    internal class SharePointPictureLibraryController : SharePointLibraryController
    {
        internal string randomWords {get; set; }
        internal int minRandomImage {get; set; }
        internal int maxRandomImage { get; set; }
        public bool GenerateContent { get; set; }

        internal const int PICTURE_LIBRARY_TEMPLATE_ID = 109;

        internal SharePointPictureLibraryController(string siteCollection) :
            base(siteCollection) { }

        internal SharePointPictureLibraryController(string siteCollection, string domain, string username, string password) :
            base(siteCollection, domain, username, password) { }

        internal List<string> CreatePictureLibraries(string baseLibraryName, int numberOfLibraries, bool deleteIfExist, bool addRandomImages, string randomWords, int minRandomImage, int maxRandomImage)
        {
            GenerateContent = addRandomImages;
            return base.CreateLibraries(baseLibraryName, PICTURE_LIBRARY_TEMPLATE_ID, numberOfLibraries, deleteIfExist);
        }

        internal override void LibraryCreated(string libraryName, int libraryIndex)
        {
            base.LibraryCreated(libraryName, libraryIndex);

            if (GenerateContent)
            {
                int numberOfImagesToGenerate = CalcNumberOfImages(minRandomImage, maxRandomImage);

                GenerateContentForLibrary(CopyClient, libraryIndex, libraryName, 0, randomWords, numberOfImagesToGenerate);
            }
        }

        internal void PopulateLibrariesWithImages(List<string> listNameList)
        {
            DoContentGenerationItemsStarted(listNameList.Count);

            // Loop through each Library and create a random number of Pics in each
            for (int i = 0; i < listNameList.Count; i++)
            {
                int numberOfImagesToGenerate = CalcNumberOfImages(minRandomImage, maxRandomImage);

                GenerateContentForLibrary(CopyClient, i, listNameList[i], listNameList.Count, randomWords, numberOfImagesToGenerate);
            }

            DoContentGenerationItemsFinished();
        }

        private static int CalcNumberOfImages(int minRandomImage, int maxRandomImage)
        {
            Random rand = new Random(DateTime.Now.Second);

            int numberOfImagesToGenerate = rand.Next(minRandomImage, maxRandomImage);
            return numberOfImagesToGenerate;
        }

        private void GenerateContentForLibrary(CopySoapClient client, int listIndex, string listName, int totalItems, string randomWords, int numberOfImagesToGenerate)
        {
            DoContentGenerationItemChanging(listName, listIndex, totalItems, Core.ContentGeneratorAction.Creating);

            PictureGenerator generator = new PictureGenerator();
            List<Picture> pics = generator.GetPhotosFromFlickr(randomWords, numberOfImagesToGenerate);

            // OK, now that we have the pictures, upload them.
            foreach (Picture pic in pics)
            {
                string newfilename = string.Format("Picture_{0}.jpg", Guid.NewGuid().ToString().Substring(0, 6));
                string imageDestinationUrl = string.Format("{0}/{1}/{2}", SiteCollection, listName, newfilename);
                string[] destinationUrlList = { imageDestinationUrl };

                CopyResult copyResult = new CopyResult();
                CopyResult[] copyResults = { copyResult };

                FieldInformation imageDescriptionFieldInfo = new FieldInformation()
                {
                    DisplayName = "Description",
                    Type = FieldType.Text,
                    Value = "This is the test description for file " + newfilename

                };
                FieldInformation imageTitleFieldInfo = new FieldInformation()
                {
                    DisplayName = "Title",
                    Type = FieldType.Text,
                    Value = "Autogenerated " + newfilename.Replace(".jpg", string.Empty)

                };

                FieldInformation[] fieldInfoArray = { imageDescriptionFieldInfo, imageTitleFieldInfo };

                MemoryStream objStream = new MemoryStream();
                pic.Image.Save(objStream, System.Drawing.Imaging.ImageFormat.Bmp);
                byte[] contentInBytes = new byte[objStream.Length];
                objStream.Position = 0;
                objStream.Read(contentInBytes, 0, Convert.ToInt32(objStream.Length));

                uint copyresult = client.CopyIntoItems(newfilename, destinationUrlList, fieldInfoArray, contentInBytes, out copyResults);

                string m = copyResults[0].ErrorMessage;
            }
        }
    }
}
